import {AddressApi} from ".././api";

export default {
        namespaced: true,
        state:{ list:[]},
        mutations:{
                init(state,list){
                        state.list=list;
                },
                remove(state,id){
                        state.list.splice(state.list.findIndex(item => item.id === id), 1);
                },
                setDefault(state,id){
                        state.list.forEach(item => item.isDefault = item.id === id?1:0);
                },
                add(state,address){
                        state.list.push(address);
                },
                update(state,address){
                        const i = state.list.findIndex(item => item.id === address.id);
                        state.list.splice(i, 1, {...address});
                }
        },
        actions:{
                async init(context){
                        const list=await AddressApi.getList();
                        context.commit("init",list);
                },
                async remove(context,id){
                        await AddressApi.remove(id);
                        context.commit('remove',id)
                },
                async setDefault(context,id){
                        await AddressApi.setDefault(id);
                        context.commit("setDefault",id)
                },
                async add(context,address){
                        const id=await  AddressApi.add(address);
                        context.commit('add',{...address,id})
                },
                async update(context,address){
                        await   AddressApi.update(address);
                        context.commit("update",{...address});

                }
        },
}
